var sqlite3 = require('sqlite3').verbose();
var enocean = require('../../core/enocean.js');
var db = new sqlite3.Database('server.db');

var id_sensor_temperature = 8991615;

exports.createModule = function (req, res) {
	
}

exports.lastOne = function(req, res){
	//TODO : take id into account 
	var id = req.params.id;
	var t = "temperature";
	if (enocean.availableSensors.indexOf(t) == -1) throw error;

	var retour = new Object();
	db.get('SELECT id_sensor, date, data FROM data WHERE id_sensor = ' + 
	'(SELECT id_source FROM source WHERE idModule=$id LIMIT 1) ORDER BY date DESC', {
		$id: id
	}, function(err, row) {
		if (err) throw err;
		if (row != undefined)
		{
			retour['id_sensor'] = row.id_sensor;
		  retour['date'] = row.date;
		  retour['value']  = JSON.parse(row.data).value;
		}
		else
		{
		  retour['error'] = 'Error, could not fetch temperature data...';
		  console.log(err);
		}
		res.end(JSON.stringify(retour));
	});
};

exports.last24h = function(req, res){
	
	//TODO : take id into account
	var id = req.params.id;

	var retour = {data:[]};
	var date24hBefore = new Date((new Date()).getTime()-86400000);

	db.each("SELECT id_sensor, date, data FROM data WHERE id_sensor = (SELECT id_source FROM source WHERE idModule=$id) AND date >= $temp", 
	{
	  $temp: date24hBefore.toISOString(),
	  $id: id
	}, function(err, row) {
		if(row != undefined)
		{
			retour['id_sensor'] = row.id_sensor;
			retour['data'].push({'date': row.date, 'value': JSON.parse(row.data).value});
		}
		else
		 	console.log("temperature/last24h: "+err);
	},
	function() // onComplete
	{
		res.end(JSON.stringify(retour));
	});
};
